package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.Settings;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private SmsTemplate template;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private BlackListApi blackListApi;

    @DubboReference
    private UserApi userApi;

    /**
     * 发送手机验证码
     *
     * @param phone：手机号
     */
    public void login(String phone) {
        //1、随机获取6位的数字验证码
        String code = RandomStringUtils.randomNumeric(6);
        // String code = "123456";
        //2、存入redis：60秒有效
        redisTemplate.opsForValue().set("CODE_" + phone, code, 1, TimeUnit.MINUTES);
        //3、发送短信
        //template.sendSms(phone,code);
        System.out.println(code);
    }


    /**
     * 用户登录
     *
     * @param phone 手机号码
     * @param code  验证码
     * @return
     */
    public Map loginVerification(String phone, String code) {
        //1、获取redis中的验证码
        String key = "CODE_" + phone;
        String value = redisTemplate.opsForValue().get(key);
        //2、判断用户登录输入的验证码和redis中的验证码是否一致
        //2.1 如果不一致：抛出异常
        if (StringUtils.isEmpty(value) || !code.equals(value)) {
            // throw new RuntimeException(); //判处异常，手机端自动判断
            throw new BusinessException(ErrorResult.loginError());
        }
        //2.2 如果验证码正确，删除redis中的验证码
        redisTemplate.delete(key);
        //3、根据手机号码查询用户
        User user = userApi.findByMobile(phone);
        //3.1 判断用户是否存在，如果不存在，创建新用户保存到tb_user表中
        Boolean isNew = false; //默认老用户
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword("123456");
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;
        }
        //4、生成token字符串（id,mobile）
        Map map = new HashMap();
        map.put("id", user.getId());
        map.put("mobile", user.getMobile());
        String token = JwtUtils.getToken(map);
        //5、构建map的返回值（token，isNew）
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap;
    }

    /**
     * 通用——查询通用设置
     *
     * @return
     */
    public SettingsVo settings() {
        //用户id和手机号码
        Long userId = UserHolder.getUserId();
        //1、查询用户的陌生人问题
        Question question = questionApi.findByUserId(userId);
        //2、查询用户的通知开关设置
        Settings settings = settingsApi.findByUserId(userId);
        //3、获取当前用户的手机号码和ID
        String mobile = UserHolder.getMobile();
        SettingsVo vo = new SettingsVo();
        vo.setStrangerQuestion(question == null ? "你喜欢java吗" : question.getTxt());
        if (settings != null) {
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
        }
        vo.setPhone(mobile);
        vo.setId(userId);
        return vo;
    }

    /**
     * 通用——陌生人问题——保存与修改
     *
     * @param content
     */
    public void saveQuestions(String content) {
        //1、获取当前用户的id
        Long userId = UserHolder.getUserId();
        //2、调用QuestionApi根据用户id查询陌生人问题
        Question question = questionApi.findByUserId(userId);
        //3、如果Question对象存在，更新
        if (question != null) {
            question.setTxt(content);
            questionApi.update(question);
        } else {
            //4、如果不存在，保存
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.save(question);
        }
    }

    /**
     * 通用——通知设置——状态开启与关闭
     *
     * @param likeNotification
     * @param pinglunNotification
     * @param gonggaoNotification
     */
    public void saveNotifications(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用API根据用户id查询通知设置
        Settings settings = settingsApi.findByUserId(userId);
        //3、如果对象存在，就更新
        if (settings != null) {
            settings.setLikeNotification(likeNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settings.setPinglunNotification(pinglunNotification);
            settingsApi.update(settings);
        } else {
            //4、不存在，保存
            settings = new Settings();
            settings.setLikeNotification(likeNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setUserId(userId);
            settingsApi.save(settings);
        }
    }

    /**
     * 通用——黑名单——分页查询
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult blacklist(Integer page, Integer pagesize) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用API分页查询数据，得到IPage对象（总数据，当前页，查询条数，数据列表）
        IPage iPage = blackListApi.findByUserId(page, pagesize, userId);
        //3、将IPage中的数据，设置到PageResult并返回
        return new PageResult(page, pagesize, iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 通用——黑名单——取消黑名单
     *
     * @param blackUserId
     */
    public void deleteBlackList(Long blackUserId) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用api删除
        blackListApi.delete(userId, blackUserId);
    }


//    public User findByMobile(String mobile) {
//        return userApi.findByMobile(mobile);
//    }
}
